#ifndef FTPPROTOCOL_H
#define FTPPROTOCOL_H

#include "ftpclient_global.h"
#include <QObject>
#include <QString>
#include <QFile>
#include <QTcpSocket>
#include <QHostAddress>

// 使用全局定义的宏，不需要再重复定义
class QTcpServer;

class FTPCLIENT_EXPORT FtpProtocol : public QObject
{
    Q_OBJECT

public:
    //FTP命令类型枚举
    enum CommandType {
        None,
        LIST,
        RETR,
        STOR
    };
    
    // 日志前缀静态常量
    static const QString LOG_PREFIX;
    
    explicit FtpProtocol(QObject *parent = nullptr);
    ~FtpProtocol();

    // 协议相关命令
    bool sendUSER(const QString &username);
    bool sendPASS(const QString &password);
    bool sendPORT();
    bool sendPASV();
    bool sendPASV2();
    bool sendLIST(const QString &path = ".");
    bool sendCWD(const QString &path);
    
private:
        QString m_downloadFilePath;
        QFile* m_downloadFile;
        QString m_currentFileName;
    
public:
    bool sendRETR(const QString &fileName, const QString &localFilePath = QString());
    bool sendSTOR(const QString &fileName);
    bool sendDELE(const QString &fileName);
    bool sendQUIT();
    bool sendFISTOR();
    void sendCommand(const QString &command);
    
    bool isDataConnectionActive() const;

    // 控制连接管理
    bool connectToHost(const QString &host, int port);
    void disconnectFromHost();
    bool isConnected() const;
    
    // 数据连接管理
    bool establishDataConnection();
    void closeDataConnection();
    QTcpSocket *dataSocket() const;

    // 响应处理
    int getResponseCode();
    QString getResponseMessage();

// 在signals部分添加下载进度信号
signals:
    void responseReceived(int code, const QString &message);
    void dataConnectionEstablished();
    void dataConnectionClosed();
    void error(const QString &message);
    void listDataReceived(const QList<QStringList>& fileInfoList);
    void fileDataReceived(const QByteArray& data);
    void dataConnectionReady();
    void controlConnectionClosed();
    void downloadProgress(qint64 bytesReceived, const QString &fileName);

private slots:
    void onControlSocketReadyRead();
    void onControlSocketDisconnected();
    void onDataSocketConnected();
    void onDataSocketDisconnected();
    void onDownloadFileFinish();
    void onDataSocketReadyRead();
    bool setupDataConnectionMode(bool usePasv, bool usePasv2);
    void initSockets();
private:
    void parseAndEmitListData(const QByteArray& data);
private:
    QTcpSocket *m_controlSocket;
    QTcpSocket *m_dataSocket;
    QString m_responseBuffer;
    bool m_isPassiveMode;
    QHostAddress m_passiveAddress;
    quint16 m_passivePort;
    bool m_isPassiveConnectionReused; // 标记是否复用被动连接
    QTcpServer * m_dataServer; // 用于主动模式监听
    quint16 m_activePort;     // 主动模式下监听的端口
    qint64 m_bytesReceived; // 当前已下载的字节数
    CommandType m_currentCommand; // 当前执行的命令类型
}; 

#endif // FTPPROTOCOL_H
